<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="dao.ProdDao"%>
<%@ page import="entity.Prod"%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="entity.CarItem" %>
<%
	String id=request.getParameter("id");
	Prod prod=new ProdDao().findProdById(Integer.parseInt(id));
	if(prod==null){
		response.sendError(404,"您所要的商品不存在！");
	}else{
		List<CarItem> shopcar=(List<CarItem>)session.getAttribute("shopcar");
		if(shopcar==null){
			shopcar=new ArrayList<CarItem>();
			CarItem ci=new CarItem();
			ci.setProd(prod);
			ci.setNum(1);
			shopcar.add(ci);
		}else{
			boolean flag = true;
			for(CarItem item :shopcar) {
				//如果购买的商品存在于购物车中
				if(item.getProd().getId() == Integer.parseInt(id)){
					//则将商品数量+1
					item.setNum(item.getNum()+1);
					flag = false;
					break;
				}
			}
			
			//如果购买的商品不存在与购物车
			if(flag) {
				//则创建新的CarItem对象
				CarItem item = new CarItem();
				item.setProd(prod);
				item.setNum(1);
				
				
				shopcar.add(item);
			}
		}
		
		
		session.setAttribute("shopcar", shopcar);
		response.sendRedirect("shopcar.jsp");
	}
	
	

%>